package service

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"insighttracking/common/utils"
	"insighttracking/query/dao"
	"insighttracking/query/model"
)

type _accountService struct{}

func (s _accountService) CreateApi(ctx context.Context, tx *dao.QueryTx, req *model.AccountEntity) error {
	// 密码加密处理
	_, err := tx.AccountEntity.WithContext(ctx).Where(dao.AccountEntity.Username.Eq(req.Username)).First()
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return errors.New("用户名已经存在")
	}
	salt := utils.GeneratorString(utils.GeneratorRandom(5, 10))
	newPassword := utils.Md5(req.Password, salt)
	if err = tx.AccountEntity.WithContext(ctx).
		Omit(dao.AccountEntity.LastLoginIP, dao.AccountEntity.LastLoginDate).
		Create(&model.AccountEntity{
			Username:     req.Username,
			Password:     newPassword,
			ParentID:     req.ParentID,
			Salt:         salt,
			Avatar:       req.Avatar,
			AccountType:  req.AccountType,
			EnterpriseID: req.EnterpriseID, // 企业id,enterprise表主键id
			CustomerID:   req.CustomerID,   // 客户id,关联到enterprise_customer表主键id
			PersonID:     req.PersonID,
		}); err != nil {
		return err
	}
	return nil

}

func (s _accountService) GetByCustomerIdApi(ctx context.Context, enterpriseId int64, customerId int64) ([]*model.AccountEntity, error) {
	return dao.AccountEntity.WithContext(ctx).Where(
		dao.AccountEntity.EnterpriseID.Eq(enterpriseId),
		dao.AccountEntity.CustomerID.Eq(customerId),
	).Find()
}

func (s _accountService) GetByAllAccountApi(ctx context.Context, enterpriseId int64) ([]*model.AccountEntity, error) {
	return dao.AccountEntity.WithContext(ctx).Where(
		dao.AccountEntity.EnterpriseID.Eq(enterpriseId),
	).Find()
}
func (s _accountService) DeleteByIdApi(ctx context.Context, tx *dao.QueryTx, id int64) error {
	if _, err := tx.AccountEntity.WithContext(ctx).Where(dao.AccountEntity.AccountID.Eq(id)).Delete(); err != nil {
		return err
	}
	return nil
}

func (s _accountService) DeleteByEnterpriseIdApi(ctx context.Context, tx *dao.QueryTx, id int64) error {
	if _, err := tx.AccountEntity.WithContext(ctx).Where(dao.AccountEntity.EnterpriseID.Eq(id)).Delete(); err != nil {
		return err
	}
	return nil
}

func (s _accountService) ModifyStatusByEnterpriseIdApi(ctx context.Context, tx *dao.QueryTx, enterpriseId int64, status int64) error {
	if _, err := tx.AccountEntity.WithContext(ctx).Where(
		dao.AccountEntity.EnterpriseID.Eq(enterpriseId),
	).UpdateSimple(dao.AccountEntity.Status.Value(status)); err != nil {
		return err
	}
	return nil
}

func (s _accountService) ModifyStatusByCustomerIdApi(ctx context.Context, tx *dao.QueryTx, enterpriseId int64, customerId int64, status int64) error {
	// 修改账号的
	if _, err := tx.AccountEntity.WithContext(ctx).Where(
		dao.AccountEntity.EnterpriseID.Eq(enterpriseId),
		dao.AccountEntity.CustomerID.Eq(customerId),
	).UpdateSimple(dao.AccountEntity.Status.Value(status)); err != nil {
		return err
	}
	return nil
}

var AccountService = new(_accountService)
